<template>
  <div>
    <Row :gutter="3" style="margin-top:10px">
      <i-col :md="5" :lg="5" :xl="5">
        <Card style="height:615px">
          <div><span style="font-size:16px;font-style:bold">画像机构选择:</span></div>
          <Tree :data="departments" ref="departmentTree" multiple show-checkbox style="margin-top:20px"></Tree>
          <Button type="primary" @click="getPortrait" style="margin-top:10px">获取部门画像</Button>
          <Spin size="large" fix v-if="loadingDepartments"></Spin>
        </Card>
      </i-col>
      <i-col :md="18" :lg="12" :xl="12">
        <Card shadow style="height:615px">
          <span v-show="portraitLoaded" style="display: inline-block; margin-right:10px; font-weight:bold;">选择画像月份:</span>
          <DatePicker v-show="portraitLoaded" type="month" :value="portraitDate" placeholder="选择画像月份" style="width: 400px"  @on-change="onDateSelected"></DatePicker>
          <Divider  v-show="portraitLoaded"></Divider>
          <v-chart v-show="portraitLoaded" :options="portraitPie" @click="pieClicked" style="height:500px;margin-top:10px;"/>
          <div style="text-align:center" v-show="!portraitLoaded">
            <img src="/images/logo.png">
            <h3>还未选择机构</h3>
          </div>
        </Card>
        <Spin size="large" fix v-if="loadingPortrait"></Spin>
      </i-col>
      <i-col :md="0" :lg="7" :xl="7">
        <Card style="height:615px">
          <Table border :columns="businessTitle" :data="businessTableData" :height="500"></Table>
          <Page show-elevator :total=tableDataTotal :page-size=pageNum :current=pageIndex @on-change="changePage" style="margin-top:10px"/>
        </Card>
        <Spin size="large" fix v-if="loadingPortrait"></Spin>
      </i-col>
    </Row>
    <Row style="margin-top:20px">
      <Card v-if="showTrend"  style="height:700px">
        <trend-line ref="trendLine" :chartData=trendLineData :options=trendLineOptions :height=600 ></trend-line>
        <Spin size="large" fix v-if="trendLoading"></Spin>
      </Card>
    </Row>
  </div>
</template>

<script>
import InforCard from '_c/info-card'
import CountTo from '_c/count-to'
import TrendLine from '_c/trend-line'
import { ChartPie, ChartBar } from '_c/charts'
import ECharts from 'vue-echarts'
import { newDateYearMonthToString, computedDateString } from '@/libs/util'
export default {
  name: 'department',
  components: {
    InforCard,
    CountTo,
    TrendLine,
    ChartPie,
    ChartBar,
    'v-chart': ECharts
  },
  data () {
    return {
      loadingDepartments: true,
      loadingPortrait: true,
      portraitLoaded: false,
      trendLoading: true,
      showTrend: false,
      currentDepartment: null,
      childDepartments: [],
      tableDataTotal: 0,
      pageTotal: 0,
      pageNum: 8,
      pageIndex: 1,
      portraitData: [],
      portraitDate: '',
      portraitPie: {
        title: {
          text: 'XXXXXX机构画像',
          subtext: 'XX月份',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          show: true,
          orient: 'vertical',
          left: 'top',
          data: ['优秀', '良好', '一般', '关注', '重点关注']
        },
        series: [
          {
            name: '画像数据',
            type: 'pie',
            radius: '75%',
            center: ['50%', '60%'],
            data: [
              { value: 0, name: '优秀' },
              { value: 0, name: '良好' },
              { value: 0, name: '一般' },
              { value: 0, name: '关注' },
              { value: 0, name: '重点关注' }
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ],
        color: [
          '#91c7ae',
          '#61a0a8',
          '#2f4545',
          '#d48265',
          '#c23531'
        ]
      },
      businessTitle: [
        {
          title: '编号',
          key: 'order',
          width: 70,
          align: 'center'
        },
        {
          title: '业务名称',
          key: 'business_name',
          align: 'center'
        },
        {
          title: '业务ID',
          key: 'data_cycle',
          align: 'center'
        }
      ],
      businessData: [],
      businessTableData: [],
      departments: [
      ],
      trendData: [],
      trendLineData: {
        type: 'line',
        labels: [],
        datasets: [
          {
            label: '优秀',
            backgroundColor: '#91C7AE',
            borderColor: '#91C7AE',
            data: [],
            fill: false
          },
          {
            label: '良好',
            backgroundColor: '#61A0A8',
            borderColor: '#61A0A8',
            data: [],
            fill: false
          },
          {
            label: '一般',
            backgroundColor: '#2F4545',
            borderColor: '#2F4545',
            data: [],
            fill: false
          },
          {
            label: '关注',
            backgroundColor: '#D48265',
            borderColor: '#D48265',
            data: [],
            fill: false
          },
          {
            label: '重点关注',
            backgroundColor: '#C23531',
            borderColor: '#C23531',
            data: [40, 39, 10, 40, 39, 80, 40, 34, 35, 21, 77, 21, 12, 11],
            fill: false
          }
        ],
        fill: false
      },
      trendLineOptions: {
        title: {
          display: true,
          text: '机构画像五级分类趋势图'
        },
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
  mounted () {
    //
    this.requestDepartment()
    this.loadingPortrait = false
  },
  methods: {
    pieClicked (event) {
      var type = event.data.name
      this.updateTable(type)
    },
    getPortrait () {
      var departmentNode = this.$refs.departmentTree.getCheckedNodes()
      if (departmentNode.length <= 0) {
        this.$Message.error('还未选择机构')
        return
      }

      var department = departmentNode[0]
      if (this.currentDepartment != null) {
        if (this.currentDepartment.id === department.id) {
          this.$Message.success('选择机构!')
          return
        }
      }

      this.currentDepartment = department
      if (!this.portraitDate) {
        this.portraitDate = newDateYearMonthToString()
      }
      this.loadingPortrait = true
      this.portraitLoaded = false
      this.businessTableData = []
      this.businessData = []
      // 获取画像数据
      this.loadingPortrait = true
      this.requestPortrait(this.currentDepartment.id, this.portraitDate)
      this.portraitLoaded = true
      this.showTrend = true
      this.requestTrendData(this.currentDepartment.id)
    },
    requestDepartment () {
      this.loadingDepartments = true
      this.axios.get('/api/v1/portrait/departments/tree').then((response) => {
        var data = response.data.data
        this.departments = this.buildDepartmentTree(data)
        this.loadingDepartments = false
      })
    },
    requestPortrait (departmentId, portraitDate) {
      this.axios.get('/api/v1/portrait/portrait', { params: {
        department_id: departmentId,
        date: portraitDate
      } }).then((response) => {
        var data = response.data.data
        this.portraitData[this.portraitDate] = this.decoratePortrait(data)
        if (portraitDate === this.portraitDate) {
          this.updatePortraitPie()
          this.loadingPortrait = false
        }
      })
    },
    decoratePortrait (data) {
      var decotratedData = []
      decotratedData['优秀'] = []
      decotratedData['良好'] = []
      decotratedData['一般'] = []
      decotratedData['关注'] = []
      decotratedData['重点关注'] = []
      // 开始装饰
      data.forEach(record => {
        decotratedData[record.evaluation_result].push(record)
      })
      return decotratedData
    },
    updatePortraitPie () {
      this.loadingPortrait = true
      var data = this.portraitData[this.portraitDate]
      // 变更名称
      this.portraitPie.title.text = this.currentDepartment.title + '机构画像'
      this.portraitPie.title.subtext = this.portraitDate.substring(5, 7) + '月份'
      // 更新数据
      this.portraitPie.series[0].data.forEach((element, index) => {
        this.portraitPie.series[0].data[index].value = data[element.name].length
      })
      this.loadingPortrait = false
    },
    buildDepartmentTree (data) {
      const result = []
      if (!Array.isArray(data)) {
        return result
      }
      data.forEach(item => {
        delete item.children
      })
      const map = {}
      data.forEach(item => {
        map[item.id] = item
      })
      data.forEach(item => {
        const parent = map[item.parent_id]
        if (parent) {
          (parent.children || (parent.children = [])).push(item)
        } else {
          result.push(item)
        }
      })
      return result
    },
    updateTable (type) {
      var data = this.portraitData[this.portraitDate][type]
      this.businessData = []
      data.forEach((record, index) => {
        record.order = index + 1
        this.businessData.push(record)
      })
      this.pageIndex = 1
      this.tableDataTotal = this.businessData.length
      var _start = (this.pageIndex - 1) * this.pageNum // pageIndex 第几页  pageNum:每页几条数据
      var _end = this.pageIndex * this.pageNum
      this.businessTableData = this.businessData.slice(_start, _end)
    },
    changePage (value) { // 改变页数
      this.pageIndex = value
      var _start = (value - 1) * this.pageNum
      var _end = value * this.pageNum
      this.businessTableData = this.businessData.slice(_start, _end)
    },
    onDateSelected (date) {
      this.portraitDate = date
      // this.getPortrait()
      this.loadingPortrait = true
      this.requestPortrait(this.currentDepartment.id, this.portraitDate)
    },
    requestTrendData (departmentId) {
      if (this.trendData[departmentId]) {
        return
      }
      this.axios.get('/api/v1/portrait/trend', { params: {
        department_id: departmentId
      } }).then((response) => {
        var data = response.data.data
        for (var i = 0; i < 12; i++) {
          var date = new Date()
          var dateStr = ''
          var year = date.getFullYear()
          var month = date.getMonth() - i
          if (month <= 0) {
            year = year - 1
            month = month + 12
          }
          if (month < 10) {
            dateStr = year + '-0' + month
          } else {
            dateStr = year + '-' + month
          }
          var decoratedData = this.decorateTrendData(data, departmentId, dateStr)
          if (!this.trendData[departmentId]) {
            this.trendData[departmentId] = []
          }
          this.trendData[departmentId][dateStr] = decoratedData[dateStr]
        }
        this.trendLoading = false
        this.updateTrendLine()
      })
    },
    updateTrendLine () {
      this.trendLoading = true
      var departmentId = this.currentDepartment.id
      if (!this.trendData[departmentId]) {
        setTimeout(function () {
          this.requestTrendData(departmentId)
        }, 3000)
        return
      }
      var data = this.trendData[departmentId]
      this.trendLineData.labels = []
      // 清楚历史数据
      this.trendLineData.datasets.forEach(element => {
        element.data = []
      })
      for (var i = 11; i >= 0; i--) {
        var date = new Date()
        var dateStr = ''
        var year = date.getFullYear()
        var month = date.getMonth() - i
        if (month <= 0) {
          year = year - 1
          month = month + 12
        }
        if (month < 10) {
          dateStr = year + '-0' + month
        } else {
          dateStr = year + '-' + month
        }
        this.trendLineData.labels.push(dateStr)
        this.trendLineData.datasets.forEach(element => {
          element.data.push(data[dateStr][element.label].length)
        })
      }
      this.trendLineOptions.title.text = this.currentDepartment.name + '机构画像五级分类变化趋势图'
      this.$refs.trendLine.renderChart(this.trendLineData, this.trendLineOptions)
      // 执行操作
      this.trendLoading = false
    },
    decorateTrendData (data, deaprtmentId, dateStr) {
      var decoratedDate = []
      decoratedDate[dateStr] = []
      decoratedDate[dateStr]['优秀'] = []
      decoratedDate[dateStr]['良好'] = []
      decoratedDate[dateStr]['一般'] = []
      decoratedDate[dateStr]['关注'] = []
      decoratedDate[dateStr]['重点关注'] = []
      // 获取日期字符串
      var targetString = computedDateString(dateStr)
      // 处理周期为月的数据
      data.forEach(element => {
        var dateString = element.record_date.substring(0, 7)
        switch (element.data_cycle) {
          case '月':
            if (dateString === targetString['month']) {
              decoratedDate[dateStr][element.evaluation_result].push(element)
            }
            break
          case '季度':
            if (dateString === targetString['quarter']) {
              decoratedDate[dateStr][element.evaluation_result].push(element)
            }
            break
          case '半年':
            if (dateString === targetString['half_year']) {
              decoratedDate[dateStr][element.evaluation_result].push(element)
            }
            break
          case '年':
            if (dateString === targetString['year']) {
              decoratedDate[dateStr][element.evaluation_result].push(element)
            }
            break
        }
      })
      return decoratedDate
    },
    showSpinLoading () {
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 18
              }
            }),
            h('div', 'Loading')
          ])
        }
      })
    },
    stopSpinLoading () {
      this.$Spin.hide()
    }
  }
}
</script>

<style lang="less">
  .count-style {
    font-size: 50px;
  }
  .ivu-tree-title{
    font-size: 14px;
  }
</style>
